package com.anyou.mall.sho.service.impl;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.anyou.common.core.domain.ApiResult;
import com.anyou.common.core.domain.entity.SysUser;
import com.anyou.common.exception.ServiceException;
import com.anyou.common.utils.DateUtils;
import com.anyou.common.utils.RedisUtil;
import com.anyou.common.utils.SecurityUtils;
import com.anyou.common.utils.StringUtils;
import com.anyou.common.utils.sign.Md5Utils;
import com.anyou.mall.dri.domain.Driver;
import com.anyou.mall.dri.mapper.DriverMapper;
import com.anyou.mall.index.param.CarPartsShopParam;
import com.anyou.mall.index.param.ShopParam;
import com.anyou.mall.index.vo.Card6Vo;
import com.anyou.mall.index.vo.ShopOrderMoneyVo;
import com.anyou.mall.order.mapper.OrdOrderMapper;
import com.anyou.mall.order.service.IOrdOrderService;
import com.anyou.mall.partner.domain.PartnerLavel;
import com.anyou.mall.partner.mapper.PartnerLavelMapper;
import com.anyou.mall.partner.service.IPartnerLavelService;
import com.anyou.mall.parts.domain.PlaPartsClassify;
import com.anyou.mall.parts.service.IPlaPartsClassifyService;
import com.anyou.mall.sho.domain.CarPartsShop;
import com.anyou.mall.sho.domain.CarPartsShopAudit;
import com.anyou.mall.sho.mapper.CarPartsShopAuditMapper;
import com.anyou.mall.sho.mapper.CarPartsShopMapper;
import com.anyou.mall.sho.param.AddPartsShopParam2;
import com.anyou.mall.sho.param.CarPartsShopDetailsParam2;
import com.anyou.mall.sho.param.EditAreaDto;
import com.anyou.mall.sho.param.IsAuthorizeAgentParam2;
import com.anyou.mall.sho.service.ICarPartsShopService;
import com.anyou.mall.sho.vo.CarPartsShopAuditListVo;
import com.anyou.mall.sho.vo.CarPartsShopDetailsVo;
import com.anyou.mall.sho.vo.CarPartsShopListVo;
import com.anyou.mall.sho.vo.SrVo;
import com.anyou.mall.use.domain.User;
import com.anyou.mall.use.mapper.UserMapper;
import com.anyou.mall.util.AssertUtils;
import com.anyou.system.domain.SysUserRole;
import com.anyou.system.mapper.SysUserMapper;
import com.anyou.system.mapper.SysUserRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jdk.nashorn.internal.AssertsEnabled;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 汽配商列表Service业务层处理
 *
 * @author gaochaohao
 * @date 2022-03-18
 */
@Service
public class CarPartsShopServiceImpl extends  ServiceImpl<CarPartsShopMapper, CarPartsShop> implements ICarPartsShopService
{
    @Autowired
    private CarPartsShopMapper carPartsShopMapper;

    @Autowired
    private PartnerLavelMapper partnerLavelMapper;
    @Autowired
    private IPartnerLavelService partnerLavelService;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private DriverMapper driverMapper;

    @Autowired
    private  ICarPartsShopService carPartsShopService;

    @Autowired
    private CarPartsShopAuditMapper carPartsShopAuditMapper;

    @Autowired
    private IOrdOrderService ordOrderService;
    @Autowired
    private OrdOrderMapper ordOrderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;


    @Autowired
    private IPlaPartsClassifyService partsClassifyService;

    /**
     * 查询汽配商列表
     *
     * @param carPartsShopId 汽配商列表主键
     * @return 汽配商列表
     */
    @Override
    public CarPartsShop selectCarPartsShopByCarPartsShopId(Long carPartsShopId)
    {
        return carPartsShopMapper.selectCarPartsShopByCarPartsShopId(carPartsShopId);
    }

    /**
     * 查询汽配商列表列表
     *
     * @param carPartsShop 汽配商列表
     * @return 汽配商列表
     */
    @Override
    public List<CarPartsShopListVo> selectCarPartsShopList(CarPartsShop carPartsShop)
    {
        return carPartsShopMapper.selectCarPartsShopList(carPartsShop);
    }

    /**
     * 新增汽配商列表
     *
     * @param carPartsShop 汽配商列表
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCarPartsShop(CarPartsShop carPartsShop)
    {

        carPartsShop.setCreateTime(DateUtils.getNowDate());

        //查找当前区域的合伙人是否存在
        CarPartsShop one = carPartsShopMapper.selectOne(new LambdaQueryWrapper<CarPartsShop>()
                .eq(CarPartsShop::getPartnerProvince, carPartsShop.getPartnerProvince())
                .eq(CarPartsShop::getPartnerCity, carPartsShop.getPartnerCity())
                .eq(CarPartsShop::getPartnerArea, carPartsShop.getPartnerArea())
                .eq(CarPartsShop::getPartnerStreet, carPartsShop.getPartnerStreet())
                .eq(CarPartsShop::getDelFlag,"0"));
        if(one!=null){
            throw new ServiceException("当前区域已存在有合伙人!");
        }
        int insert = carPartsShopMapper.insert(carPartsShop);
        if(insert>0){
            //添加一条到后台用户表sys_user中
            SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getUserName, carPartsShop.getAccountNumber()));
            if(sysUser==null){
                sysUser = new SysUser();
                sysUser.setNickName(carPartsShop.getContactName());
                sysUser.setUserName(carPartsShop.getAccountNumber());
                //合伙人后台用户的初始密码值123456
                sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
                sysUser.setUserType("11");
                sysUser.setCarPartsShopId(carPartsShop.getCarPartsShopId());
                sysUser.setCreateTime(DateUtils.getNowDate());
                sysUserMapper.insert(sysUser);
                //再给当前系统用户绑定合伙人角色
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(sysUser.getUserId());
                sysUserRole.setRoleId(100L);//合伙人的角色id为100
                sysUserRoleMapper.insert(sysUserRole);
            }else{
                throw new ServiceException("已存在与此账号的后台管理员，请换个账号!");
            }

            //添加一条到司机表dri_driver中，
            Driver driver = driverMapper.selectOne(new LambdaQueryWrapper<Driver>()
                    .eq(Driver::getAccount, carPartsShop.getAccountNumber()));
            if(driver==null){
                driver = new Driver();
                driver.setIndividualAuditName(carPartsShop.getContactName());
                driver.setAccount(carPartsShop.getAccountNumber());
                driver.setIndividualAuditPhone(carPartsShop.getAccountNumber());
                driver.setPassword(carPartsShop.getLoginPassword());
                driver.setUserType(1);
                driver.setCreateTime(DateUtils.getNowDate());
                driver.setSysUserId(sysUser.getUserId());
                driver.setPartnerId(carPartsShop.getCarPartsShopId());
                driverMapper.insert(driver);
            }else{
                throw new ServiceException("已存在与当前账号相同的司机，请换个账号!");
            }
            //查看司机表中是否有后台管理员，如果没有就添加一个
            Driver admin = driverMapper.selectOne(new LambdaQueryWrapper<Driver>()
                    .eq(Driver::getAccount,"admin"));
            if(admin==null){
                //查询系统管理员
                SysUser adminSysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUserName, "admin"));
                if(adminSysUser==null){
                    throw new ServiceException("admin系统管理员不存在");
                }
                admin = new Driver();
                admin.setIndividualAuditName("管理员");
                admin.setAccount("admin");
                admin.setIndividualAuditPhone("admin");
                //管理员手机端密码初始值
                admin.setPassword(Md5Utils.hash("admin123"));
                admin.setUserType(2);
                admin.setCreateTime(DateUtils.getNowDate());
                admin.setSysUserId(adminSysUser.getUserId());
                driverMapper.insert(admin);
            }
            //查询手机端是否有用户
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getPhoneNumber, carPartsShop.getAccountNumber()));
            if(user!=null){
                user.setUserType(1L);
                userMapper.updateById(user);
            }else{
                //如果没有就新增
                user = new User();
                //合伙人小程序端密码初始值
                user.setLoginPassword(Md5Utils.hash("123456"));
                user.setPhoneNumber(carPartsShop.getAccountNumber());
                user.setUserType(1L);
                user.setNickName(carPartsShop.getContactName());
                userMapper.insert(user);
            }

        }
        return 1;
    }

    /**
     * 修改汽配商列表
     *
     * @param param 合伙人
     * @return 结果
     */
    @Override
    public int updateCarPartsShop(AddPartsShopParam2 param)
    {
        CarPartsShop carPartsShop = carPartsShopMapper.selectById(param.getCarPartsShopId());
        if(carPartsShop==null){
           throw new ServiceException("合伙人不存在") ;
        }
        //查找当前区域的合伙人
        if(StringUtils.isNotEmpty(param.getPartnerProvince())
            &&StringUtils.isNotEmpty(param.getPartnerCity())
            &&StringUtils.isNotEmpty(param.getPartnerArea())
                &&StringUtils.isNotEmpty(param.getPartnerStreet())
                ){
            CarPartsShop one = carPartsShopMapper.selectOne(new LambdaQueryWrapper<CarPartsShop>()
                    .eq(CarPartsShop::getPartnerProvince, param.getPartnerProvince())
                    .eq(CarPartsShop::getPartnerCity, param.getPartnerCity())
                    .eq(CarPartsShop::getPartnerArea, param.getPartnerArea())
                    .eq(CarPartsShop::getPartnerStreet, param.getPartnerStreet()));
            if(!one.getCarPartsShopId().toString().equals(param.getCarPartsShopId().toString())){
                throw new ServiceException("当前区域合伙人已存在，无法修改到当前区域") ;
            }
        }

        BeanUtils.copyProperties(param,carPartsShop);
        carPartsShop.setUpdateTime(DateUtils.getNowDate());
        return carPartsShopMapper.updateById(carPartsShop);
    }

    /**
     * 批量删除汽配商列表
     *
     * @param carPartsShopIds 需要删除的汽配商列表主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteCarPartsShopByCarPartsShopIds(Long[] carPartsShopIds)
    {
        int i = carPartsShopMapper.deleteBatchIds(Arrays.asList(carPartsShopIds));
        if(i>0){
            //删除司机表中的合伙人
            int delete = driverMapper.delete(new LambdaQueryWrapper<Driver>()
                    .eq(Driver::getDriverType, 1)
                    .in(Driver::getPartnerId, carPartsShopIds));
            //删除系统用户表中的合伙人·
            int delete1 = sysUserMapper.delete(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getUserType, "11")
                    .in(SysUser::getCarPartsShopId, carPartsShopIds));
        }
        return 1;
    }

    /**
     * 删除汽配商列表信息
     *
     * @param carPartsShopId 汽配商列表主键
     * @return 结果
     */
    @Override
    public int deleteCarPartsShopByCarPartsShopId(Long carPartsShopId)
    {
        return carPartsShopMapper.deleteCarPartsShopByCarPartsShopId(carPartsShopId);
    }

    @Override
    public ApiResult updateEnableStatus(Long carPartsShopId) {
        CarPartsShop carPartsShop = carPartsShopMapper.selectCarPartsShopByCarPartsShopId(carPartsShopId);
        if (carPartsShop != null) {
            if ("1".equals(carPartsShop.getEnableStatus())) {
                carPartsShop.setEnableStatus("0");
            } else {
                carPartsShop.setEnableStatus("1");
            }
            return ApiResult.success(carPartsShopMapper.updateCarPartsShop(carPartsShop));
        } else {
            return ApiResult.error("修改失败");
        }
    }

    @Override
    public ApiResult updateIsHomeRecommend(Long carPartsShopId) {
        CarPartsShop carPartsShop = carPartsShopMapper.selectCarPartsShopByCarPartsShopId(carPartsShopId);
        if (carPartsShop != null) {
            if ("1".equals(carPartsShop.getIsHomeRecommend())) {
                carPartsShop.setIsHomeRecommend("0");
            } else {
                carPartsShop.setIsHomeRecommend("1");
            }
            return ApiResult.success(carPartsShopMapper.updateCarPartsShop(carPartsShop));
        } else {
            return ApiResult.error("修改失败");
        }
    }

    @Override
    public List<CarPartsShop> getAllList(CarPartsShop carPartsShop) {
        List<CarPartsShop> list = carPartsShopMapper.selectAll(carPartsShop);
        return list;
    }

    @Override
    public CarPartsShop selectCarPartsShopDetailsByCarPartsShopId(Long carPartsShopId) {


        CarPartsShop carPartsShop = carPartsShopMapper.selectById(carPartsShopId);
        PartnerLavel partnerLavel = partnerLavelMapper.selectById(carPartsShop.getLavelId());
        if(partnerLavel!=null){
            carPartsShop.setLavelName(partnerLavel.getLavelName());
        }
        return carPartsShop;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult shopAdminUpdate(CarPartsShopAudit carPartsShopAudit) {

        int i = carPartsShopAuditMapper.updateById(carPartsShopAudit);
        if(i>0){
            //修改汽配商表
            if(carPartsShopAudit.getBusinessHoursSta()!=null||carPartsShopAudit.getBusinessHoursEnd()!=null){
                //查询汽配商表
                CarPartsShop one = this.getOne(new QueryWrapper<CarPartsShop>().lambda()
                        .eq(CarPartsShop::getCarPartsShopAuditId, carPartsShopAudit.getCarPartsShopAuditId()));
                if(one!=null){
                    if(carPartsShopAudit.getBusinessHoursSta()!=null){
                        one.setBusinessHoursSta(carPartsShopAudit.getBusinessHoursSta());
                    }
                    if(carPartsShopAudit.getBusinessHoursEnd()!=null){
                        one.setBusinessHoursEnd(carPartsShopAudit.getBusinessHoursEnd());
                    }
                    if(StringUtils.isNotEmpty(carPartsShopAudit.getShopStyle())){
                        one.setShopStyle(carPartsShopAudit.getShopStyle());
                    }
                    if(StringUtils.isNotEmpty(carPartsShopAudit.getSynopsisInfo())){
                        one.setSynopsisInfo(carPartsShopAudit.getSynopsisInfo());
                    }
                    if(StringUtils.isNotEmpty(carPartsShopAudit.getMainCategory())){
                        one.setMainCategory(carPartsShopAudit.getMainCategory());
                    }
                    if(StringUtils.isNotEmpty(carPartsShopAudit.getMainProducts())){
                        one.setMainProducts(carPartsShopAudit.getMainProducts());
                    }
                    this.updateById(one);
                }
            }
        }
        return ApiResult.success();
    }
    /**
     * 商家首页6个卡片统计数量
     * @param shopParam
     * @return
     */
    @Override
    public ApiResult<Card6Vo> card6(ShopParam shopParam) {
        CarPartsShop cps = carPartsShopMapper.selectById(shopParam.getCarPartsShopId());
        AssertUtils.isNull(cps, "该合伙人不存在");
        //排名，水票数，总销售额，总订单数，待发货订单数，待处理订单数
        Card6Vo card6Vo = new Card6Vo(0, new BigDecimal(0), 0, 0, 0, 0);
        //查询水票数
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhoneNumber, cps.getAccountNumber()));

        //计算排名
        Integer myRank = partnerLavelService.getMyRank(shopParam.getCarPartsShopId());
        card6Vo.setRankNum(myRank);
        if(user!=null){
            card6Vo.setWaterTicketNum(user.getWaterTicketNum());
        }
        //查询总收入,与总销售金额,总入账,总抽拥,总出账
        ShopOrderMoneyVo shopOrderMoneyVo=ordOrderService.getTotalMoney(shopParam.getCarPartsShopId());
        if (shopOrderMoneyVo != null) {
            //查询总订单数量,待发货订单数量,待处理售后订单数量
            Card6Vo card6Vo0= ordOrderService.getTjOrderNum(shopParam.getCarPartsShopId());
            BeanUtils.copyProperties(shopOrderMoneyVo,card6Vo0);
            card6Vo0.setRankNum(card6Vo.getRankNum());
            card6Vo0.setWaterTicketNum(card6Vo.getWaterTicketNum());
            return ApiResult.success(card6Vo0);
        }

        return ApiResult.success(card6Vo);

    }

    @Override
    public ApiResult updateAuthorizeAgent(IsAuthorizeAgentParam2 isAuthorizeAgentParam2) {

        CarPartsShop carPartsShop = carPartsShopService.getOne(new LambdaQueryWrapper<CarPartsShop>().eq(CarPartsShop::getCarPartsShopAuditId, isAuthorizeAgentParam2.getCarPartsShopAuditId()));
        if(carPartsShop != null) {
            carPartsShop.setIsAuthorizeAgent(isAuthorizeAgentParam2.getAuthorizeStatus());
            return ApiResult.success(carPartsShopMapper.updateCarPartsShop(carPartsShop));
        } else {
            return ApiResult.error();
        }
    }
    /**
     * 获取商家总销售额与总销售次数
     * @param userId
     * @return
     */
    @Override
    public SrVo getSrxl(Long userId) {
        SrVo srVo = new SrVo(0d,0);
        SrVo sr0 = ordOrderMapper.selectSr(userId);
        if(sr0!=null){
            srVo=sr0;
        }
        return srVo;
    }
    /**
     * 修改合伙人区域
     * @param param
     */
    @Override
    public void editArea(EditAreaDto param) {
        CarPartsShop carPartsShop = carPartsShopMapper.selectById(param.getCarPartsShopId());
        if(carPartsShop==null){
            throw new ServiceException("当前合伙人不存在");
        }
        carPartsShop.setPartnerProvince(param.getPartnerProvince());
        carPartsShop.setPartnerCity(param.getPartnerCity());
        carPartsShop.setPartnerArea(param.getPartnerArea());
        carPartsShop.setPartnerStreet(param.getPartnerStreet());
        carPartsShopMapper.updateById(carPartsShop);
    }

    /**
     * 会员等级
     * @return
     */
    @Override
    public List<PartnerLavel> getLavelList() {
        List<PartnerLavel> partnerLavels = partnerLavelMapper.selectList(new LambdaQueryWrapper<PartnerLavel>());
        return partnerLavels;
    }
    /**
     * 验证手机验证码
     * @param phone
     * @param code
     */
    @Override
    public void yzCode(String phone, String code) {
        String value = redisUtil.getValue(phone);
        if (value != null){
            throw new ServiceException("验证码已过期");
        }
        if (!code.equals(value)){
            throw new ServiceException("验证码错误");
        }

    }

}
